package com.ucap.spyxmp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;
import com.ucap.spyxmp.data.RestResultBuilder;
import com.ucap.spyxmp.data.ResultModel;
import com.ucap.spyxmp.model.*;
import com.ucap.util.*;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.*;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/5/14.
 */
public class FileController extends Controller {

    public void licensePath() {
        ResultModel resultModel;

        WxWsbsUser user = Conts.getSessionUser(getSession());

        if (user == null) {
            renderJson(RestResultBuilder.builder().noLogin().build());
        } else if (StringUtils.isEmpty(getPara("sblsh"))) {

            renderJson(RestResultBuilder.builder().failure().message("传入参数有误").build());
        } else {

            try {
                String sblsh = getPara("sblsh");
                List<WxWsbsFile> fileList = WxWsbsFile.me.findLicenseFileList(user.getStr("id"), sblsh);
                System.out.println("材料数量" + fileList.size());
                if(fileList.size() == 0){

                    resultModel = RestResultBuilder.builder().failure().message("没有相关数据").build();
                }else{

                    resultModel = RestResultBuilder.builder().success().data(fileList).build();
                }

            } catch (Exception e) {
                resultModel = RestResultBuilder.builder().failure().build();
                e.printStackTrace();
            }
            renderJson(resultModel);
        }
    }

    public void uploadSignature() {

        WxWsbsUser user = Conts.getSessionUser(getSession());

        if(user == null){
            renderJson(RestResultBuilder.builder().noLogin().build());
        }else {
            ResultModel resultModel;
            try {
                String uploadPath = user.getStr("id") + "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay();
                UploadFile file = getFile("file", uploadPath);
                if (StringUtils.isEmpty(getPara("tableName"))) {
                    renderJson(RestResultBuilder.builder().failure().message("传入参数有误").build());
                } else if(!StringUtils.isEmpty(getPara("sblsh"))){
                    renderJson(RestResultBuilder.builder().failure().message("已提交申请，不能上传文件").build());
                }else{
                    //删除之前的签名数据
                    WxWsbsFile.me.deleteSignature(user.getStr("id"));
                    WxWsbsFile wsbsFile = new WxWsbsFile();
                    wsbsFile.set("ID", StringUtils.getUUID());
                    wsbsFile.set("USERID", user.getStr("id"));
                    wsbsFile.set("FILEPATH", "/files/upload/" + uploadPath + "/" + file.getFileName());
                    wsbsFile.set("FILENAME", file.getFileName());
                    wsbsFile.set("CONTENTTYPE", file.getContentType());
                    wsbsFile.set("TABLENAME", "SIGNATURE");
                    wsbsFile.set("FILESIZE", getPara("fileSize"));
                    wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
                    wsbsFile.set("ADDUSER", Conts.getSessionUser(getSession()).get("id"));
                    wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
                    wsbsFile.set("UPDATEUSER", Conts.getSessionUser(getSession()).get("id"));
                    wsbsFile.set("DATASTATE", "I");

                    boolean boo = wsbsFile.save();
                    if (boo) {
                        resultModel = RestResultBuilder.builder().success().data(wsbsFile).build();
                    } else {
                        resultModel = RestResultBuilder.builder().failure().message("上传材料失败").build();
                    }
                    renderJson(resultModel);
                }
            } catch (Exception e) {
                e.printStackTrace();
                renderJson(RestResultBuilder.builder().failure().message("上传材料失败").build());
            }
        }
    }

    public void upload() {

        WxWsbsUser user = Conts.getSessionUser(getSession());

        if(user == null){
            renderJson(RestResultBuilder.builder().noLogin().build());
        }else {
            ResultModel resultModel;
            try {
                String uploadPath = user.getStr("id") + "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay();
                UploadFile file = getFile("file", uploadPath);
                if (StringUtils.isEmpty(getPara("tableName"))) {
                    renderJson(RestResultBuilder.builder().failure().message("传入参数有误").build());
                } else if(!StringUtils.isEmpty(getPara("sblsh"))){
                    renderJson(RestResultBuilder.builder().failure().message("已提交申请，不能上传文件").build());
                }else{
                    WxWsbsFile wsbsFile = new WxWsbsFile();
                    wsbsFile.set("ID", StringUtils.getUUID());
                    wsbsFile.set("USERID", user.getStr("id"));
                    wsbsFile.set("FILEPATH", "/files/upload/" + uploadPath + "/" + file.getFileName());
                    wsbsFile.set("FILENAME", file.getFileName());
                    wsbsFile.set("CONTENTTYPE", file.getContentType());
                    wsbsFile.set("TABLENAME", getPara("tableName"));
                    wsbsFile.set("FILESIZE", getPara("fileSize"));
                    wsbsFile.set("ADDTIME", new DateTime().getTimestamp());
                    wsbsFile.set("ADDUSER", Conts.getSessionUser(getSession()).get("id"));
                    wsbsFile.set("UPDATETIME", new DateTime().getTimestamp());
                    wsbsFile.set("UPDATEUSER", Conts.getSessionUser(getSession()).get("id"));
                    wsbsFile.set("DATASTATE", "I");

                    boolean boo = wsbsFile.save();
                    if (boo) {
                        resultModel = RestResultBuilder.builder().success().data(wsbsFile).build();
                    } else {
                        resultModel = RestResultBuilder.builder().failure().message("上传材料失败").build();
                    }
                    renderJson(resultModel);
                }
            } catch (Exception e) {
                e.printStackTrace();
                renderJson(RestResultBuilder.builder().failure().message("上传材料失败").build());
            }
        }
    }

    public void query() {
        ResultModel resultModel;

        WxWsbsUser user = Conts.getSessionUser(getSession());

        if(user == null){

            renderJson(RestResultBuilder.builder().noLogin().build());
        } else if (StringUtils.isEmpty(getPara("tableName"))) {

            renderJson(RestResultBuilder.builder().failure().message("传入参数有误").build());
        }else{

            try {
                String sblsh = getPara("sblsh");
                if(sblsh != null && !"".equals(sblsh)){
                    List<WxWsbsFile> fileList = WxWsbsFile.me.findFileListByTableNameAndUserId(getPara("tableName"), user.getStr("id"), sblsh);
                    System.out.println("材料数量" + fileList.size());
                    resultModel = RestResultBuilder.builder().success().data(fileList).build();
                }else{
                    List<WxWsbsFile> fileList = WxWsbsFile.me.findFileListByTableNameAndUserId(getPara("tableName"), user.getStr("id"));
                    System.out.println("材料数量" + fileList.size());
                    resultModel = RestResultBuilder.builder().success().data(fileList).build();
                }

            } catch (Exception e) {
                resultModel = RestResultBuilder.builder().failure().build();
                e.printStackTrace();
            }
            renderJson(resultModel);
        }
    }

    public void del() {
        JSONObject msg = new JSONObject();
        if (!StringUtils.isEmpty(getPara("id"))) {

            WxWsbsFile file = WxWsbsFile.me.findById(getPara("id"));

            if(file.get("SBLSH") != null){

                SpyxmpApplyItem applyItem = SpyxmpApplyItem.me.findBySblsh(file.getStr("SBLSH"));

                if(applyItem == null || "0".equals(applyItem.getStr("STATUS"))){

                    boolean boo = file.delete();
                    msg.put("success", boo);
                    if (boo) {
                        msg.put("msg", "删除材料成功");
                    } else {
                        msg.put("msg", "删除材料失败");
                    }
                }else{
                    msg.put("success", false);
                    msg.put("msg", "已提交信息，不能删除材料");
                }

            }else{

                boolean boo = file.delete();
                msg.put("success", boo);
                if (boo) {
                    msg.put("msg", "删除材料成功");
                } else {
                    msg.put("msg", "删除材料失败");
                }
            }
        }
        renderJson(msg);
    }


    private String createSpyxFileWord(String sblsh) {
        String uploadPath = "/" + new DateTime().getYear() + "/" + new DateTime().getMonth() + "/" + new DateTime().getDay()+"/" +System.currentTimeMillis();

        String filePth = PathKit.getWebRootPath()+"/files/upload/" + uploadPath + "/" +sblsh+ ".doc";
        try {
            /** 初始化配置文件 **/
            Configuration configuration = new Configuration();
            /** 设置编码 **/
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassicCompatible(true);//设置属性
            /** 加载文件 **/
            configuration.setDirectoryForTemplateLoading(new File(PathKit.getWebRootPath() + "/files/download/freemarker/form/spyxmp"));
            /** 加载模板 **/
            Template template = null;
            /** 准备数据 **/
            Map<String, Object> dataMap = new HashMap<>();

            /** 表格数据初始化 **/
            System.out.println(sblsh);
            SpyxmpApplyItem item = SpyxmpApplyItem.me.findBySblsh(sblsh);
            //数据对应表名称（1：食品经营许可证 2：药品经营许可证 3：第二类医疗器械经营备案凭证 4：医疗器械经营许可证）
            if (item.getStr("TABLENAME").equals("SPYXMP_SPJYXKZ")) {
                SpyxmpSpjyxkz data = SpyxmpSpjyxkz.me.findByApplyId(item.getStr("SBLSH"));
                List paras = new ArrayList();
                paras.add(item.getStr("SBLSH"));
                paras.add("SIGNATURE");
                WxWsbsFile file = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                //电子签名转化base64字符串
                System.out.println( Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("signature",Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("date", DateUtil.fomatDateYMD(data.getStr("ADDTIME").substring(0, data.getStr("ADDTIME").indexOf("."))));
                dataMap.put("data", data);
                if ("1".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("spbfzxsqb.ftl");
                } else if ("2".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("spbfzxsqb.ftl");
                } else if ("3".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("spyxbgsqb.ftl");
                } else if ("4".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("spyxbgsqb.ftl");
                }
            } else if (item.getStr("TABLENAME").equals("SPYXMP_YPJYXKZ")) {

                SpyxmpYpjyxkz data = SpyxmpYpjyxkz.me.findByApplyId(item.getStr("SBLSH"));
                List paras = new ArrayList();
                paras.add(item.getStr("SBLSH"));
                paras.add("SIGNATURE");
                WxWsbsFile file = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                //电子签名转化base64字符串
                System.out.println( Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("signature",Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.set("FZRQ", DateUtil.fomatDateYMD(data.getStr("FZRQ")));
                data.put("date", DateUtil.fomatDateYMD(data.getStr("ADDTIME").substring(0, data.getStr("ADDTIME").indexOf("."))));

                dataMap.put("data", data);
                if ("1".equals(data.getStr("TYPE"))) {
                    dataMap.put("yyyy",DateUtil.format(DateUtil.formatDate(data.getStr("SMRQ")),"yyyy"));
                    dataMap.put("MM",DateUtil.format(DateUtil.formatDate(data.getStr("SMRQ")),"MM"));
                    dataMap.put("dd",DateUtil.format(DateUtil.formatDate(data.getStr("SMRQ")),"dd"));
                    template = configuration.getTemplate("ypbfsqb.ftl");
                } else if ("2".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("ypzxsqb.ftl");
                }
            } else if (item.getStr("TABLENAME").equals("SPYXMP_DELYLQXJYBAPZ")) {


                SpyxmpDelylqxjybapz data = SpyxmpDelylqxjybapz.me.findByApplyId(item.getStr("SBLSH"));
                List paras = new ArrayList();
                paras.add(item.getStr("SBLSH"));
                paras.add("SIGNATURE");
                WxWsbsFile file = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                //电子签名转化base64字符串
                System.out.println( Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("signature",Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("date", DateUtil.fomatDateYMD(data.getStr("ADDTIME").substring(0, data.getStr("ADDTIME").indexOf("."))));
                dataMap.put("data", data);
                if ("1".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("elqxbfsqb.ftl");
                } else if ("2".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("elqxbfsqb.ftl");
                }
            } else if (item.getStr("TABLENAME").equals("SPYXMP_YLQXJYXKZ")) {

                SpyxmpYlqxjyxkz data = SpyxmpYlqxjyxkz.me.findByApplyId(item.getStr("SBLSH"));
                List paras = new ArrayList();
                paras.add(item.getStr("SBLSH"));
                paras.add("SIGNATURE");
                WxWsbsFile file = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                //电子签名转化base64字符串
                System.out.println( Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("signature",Base64Utils.getImageStr(PathKit.getWebRootPath() + file.getStr("FILEPATH")));
                data.put("date", DateUtil.fomatDateYMD(data.getStr("ADDTIME").substring(0, data.getStr("ADDTIME").indexOf("."))));
                data.set("FZRQ", DateUtil.fomatDateYMD(data.getStr("FZRQ")));
                dataMap.put("data", data);
                if ("1".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("qxbfsqb.ftl");
                } else if ("2".equals(data.getStr("TYPE"))) {
                    template = configuration.getTemplate("qxzxsqb.ftl");
                }
            }

            /** 指定输出word文件的路径 **/

            File docFile = new File(filePth);
            if (!docFile.getParentFile().exists()) {
                docFile.getParentFile().mkdirs();//不存在则创建父目录
                docFile.createNewFile();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile), "UTF-8"));
            // isNullOrEmpty(dataMap);
            template.process(dataMap, out);


            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePth;
    }

    /**
     * 下载word
     *
     * @throws Exception
     */
    public void downloadSpyxWord() {
        String sblsh = getPara("sblsh");
        List paras = new ArrayList();
        //createFileWord(sblsh);
        if (!StringUtils.isEmpty(sblsh)) {
            paras.add(sblsh);
            paras.add("dzsqb");
        }
        try {
            String rootPath = PathKit.getWebRootPath();
            if (sblsh != null) {
                /*WxWsbsFile tjctInfo = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                if(tjctInfo==null){

                    tjctInfo = WxWsbsFile.me.findWordBysblshAndTableName(paras);
                }
                String filePath = rootPath + tjctInfo.getStr("FILEPATH");*/
                String filePath = createSpyxFileWord(sblsh);
                String fileName = sblsh + ".doc";
                FileDownload.fileDownload(this.getResponse(), filePath, fileName);
            }
        } catch (IOException io) {
            io.printStackTrace();
            System.out.println("word下载失败");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("word下载失败");
        }
    }
}
